import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.Socket;

public class ClientGUI extends JFrame {
    private JTextArea chatArea;
    private JTextField inputField;
    private PrintWriter out;
    private BufferedReader in;

    public ClientGUI(String serverIp) {
        setTitle("聊天客户端");
        setSize(600, 500);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        chatArea = new JTextArea();
        chatArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(chatArea);
        add(scrollPane, BorderLayout.CENTER);

        JPanel inputPanel = new JPanel(new BorderLayout());
        inputField = new JTextField();
        JButton sendButton = new JButton("发送");
        inputPanel.add(inputField, BorderLayout.CENTER);
        inputPanel.add(sendButton, BorderLayout.EAST);
        add(inputPanel, BorderLayout.SOUTH);

        // 发送按钮事件
        sendButton.addActionListener(e -> sendMessage(inputField.getText()));
        inputField.addActionListener(e -> sendMessage(inputField.getText()));

        connectServer(serverIp);
        setVisible(true);
    }

    private void connectServer(String serverIp) {
        try {
            Socket socket = new Socket(serverIp, 12345);
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            // 启动线程收消息
            new Thread(() -> {
                String message;
                try {
                    while ((message = in.readLine()) != null) {
                        appendMessage(message); 
                    }
                } catch (IOException e) {
                    appendMessage("连接断开：" + e.getMessage());
                }
            }).start();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this, "连接失败：" + e.getMessage());
            System.exit(1);
        }
    }

    private void sendMessage(String msg) {
        if (msg.trim().isEmpty()) return;
        out.println(msg); 
        appendMessage("我: " + msg); 
        inputField.setText("");
    }

    private void appendMessage(String msg) {
        chatArea.append(msg + "\n");
        chatArea.setCaretPosition(chatArea.getDocument().getLength());
    }

    public static void main(String[] args) {
        String serverIp = JOptionPane.showInputDialog("服务器IP（默认localhost）", "localhost");
        SwingUtilities.invokeLater(() -> new ClientGUI(serverIp));
    }
}